<template>
  <el-form :ref="formName + 'setting_form'" label-width="80px" :model="form">
    <el-form-item
      v-for="item in form"
      :key="item.name"
      :label="item.title"
      :prop="item.rule ? item.name + '.value' : ''"
      :rules="item.rule ? item.rule : []"
    >
      <VanFormItem :ref="item.name" :item-data="item" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit(formName)">确认保存</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
  import VanFormItem from './VanFormItem.vue'
  import { doEdit } from '@/api/setting'
  export default {
    components: { VanFormItem },
    props: {
      formData: {
        type: Object,
        default: () => ({}),
      },
      formName: {
        type: String,
        default: '',
      },
    },
    data() {
      return {
        form: {},
      }
    },
    watch: {
      formData: {
        handler(val) {
          console.log(val)
          if (val) this.form = val
        },
        // 代表在wacth里声明了firstName这个方法之后立即先去执行handler方法
        immediate: true,
      },
    },
    methods: {
      onSubmit(formName) {
        console.log(this.form)
        this.$refs[formName + 'setting_form'].validate(async (valid) => {
          if (valid) {
            const { message } = await doEdit(this.form)
            this.$baseMessage(message, 'success')
          } else {
            return false
          }
        })
      },
    },
  }
</script>
<style>
  .el-form-item__error {
    padding-left: 10px;
  }
</style>
